package cn.chencaiju.day09;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

import org.junit.Test;

public class ExceptionChecked {
	private static final String url="E:\\camp\\camp\\code\\src\\cn\\chencaiju\\day08\\Car.java";
	
	/*
	 * 在指定路径创建文件
	 */
	@Test public void testCheckedException() {
		File f=new File("x:\\ddd.java");
		try {
			f.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("处理异常完毕！");
	}
	
	@Test public void testFileRead() {
		FileReader reader=null;
		try {
			reader=new FileReader(url);
			char[] chars=new char[10];
			int count=reader.read(chars);
			System.out.println(count+Arrays.toString(chars));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(reader!=null)
					reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/*
	 * 不需要在finally处关闭资源，优化代码
	 */
	@Test public void testFileReader() {

		try(FileReader reader = new FileReader(url)){
			char[] chars=new char[10];
			int count=reader.read(chars);
			System.out.println(count+Arrays.toString(chars));			
		}catch(FileNotFoundException e) {
			e.printStackTrace();
		}catch(IOException e) {
			e.printStackTrace();
		}
	}
	
	/*
	 * 将异常处理交给调用者实现
	 */
	@Test public void testFileReader2() throws IOException {
		FileReader reader=null;
		reader=new FileReader(url);
		char[] chars=new char[10];
		int count=reader.read(chars);
		System.out.println(count+Arrays.toString(chars));
		reader.close();
	}
}
